
import React, { useEffect, useRef } from 'react';
import { useImmer } from 'use-immer';
export interface ILazyState<P extends {} = {}> {
  Cls?: React.ComponentType<P>,
  error?: any,
}
export interface ILazyFn<P> {
  (): Promise<{ default: React.ComponentType<P> }>
}

/**
 * 发现如下现象，HashRouter时，React.lazy会导致首次加载页面刷新一次，用此代替之
 *
 * 发生版本
 * react@19.1.0
 * react-dom@19.1.0
 * react-router@7.5.3
 * 
 * @export
 * @template P
 * @param {ILazyFn<P>} fn
 * @return {*}  {React.ComponentType<P>}
 */
export default function Lazy<P extends {} = {}>(fn: ILazyFn<P>): React.ComponentType<P> {
  return (props: P) => {
    const ref_status = useRef(0);
    const [{ Cls }, set_state] = useImmer<ILazyState<P>>(() => ({}))
    useEffect(() => {
      if (ref_status.current != 0) return;
      ref_status.current = 1;
      fn().then((cls) => {
        ref_status.current = 2;
        set_state({ Cls: cls.default })
      }).catch(error => {
        ref_status.current = 3;
        set_state({ error })
      });
    }, []);

    return Cls ? <Cls {...props} /> : <></>;
  };
}
